package com.cn.shuangzi.ad.view;


import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import com.cn.shuangzi.SZBaseActivity;
import com.cn.shuangzi.SZBaseFragment;
import com.cn.shuangzi.ad.R;
import com.cn.shuangzi.ad.bean.RemoveAdRewardVideoTaskInfo;
import com.cn.shuangzi.ad.manager.AdRewardManager;
import com.cn.shuangzi.ad.util.ADUtil;
import com.cn.shuangzi.util.SZDateUtil;
import com.cn.shuangzi.util.SZToast;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.view.pop.BasePop;

import androidx.annotation.NonNull;

/**
 * Created by CN.
 */
public class RewardVideoRemoveAdPop extends BasePop {
    private View lltRemoveAdTime;
    private TextView txtTime;
    private TextView txtWait1;
    private TextView txtDone1;
    private TextView txtWatch1;
    private View viewDone1;
    private View viewCurrent1;
    private TextView txtWait2;
    private TextView txtDone2;
    private TextView txtWatch2;
    private View viewDone2;
    private View viewCurrent2;
    private TextView txtWait3;
    private TextView txtDone3;
    private TextView txtWatch3;
    private View viewDone3;
    private View viewCurrent3;
    private TextView txtWait4;
    private TextView txtDone4;
    private TextView txtWatch4;
    private View viewDone4;
    private View viewCurrent4;
    private TextView txtWait5;
    private TextView txtDone5;
    private TextView txtWatch5;
    private View viewDone5;
    private View viewCurrent5;

    private RemoveAdRewardVideoTaskInfo currentTaskInfo;
    private OnRewardDealListener onRewardDealListener;
    private SZBaseFragment fragment;
    private SZBaseActivity activity;

    public interface OnRewardDealListener {
        void onCloseRemoveAdView();
    }

    /**
     * 以免广告小时时长 赋值taskId
     */
    public static final int TASK_ID_1 = 1;
    public static final int TASK_ID_2 = 3;
    public static final int TASK_ID_3 = 6;
    public static final int TASK_ID_4 = 12;
    public static final int TASK_ID_5 = 24;

    private String adUnitId;

    public RewardVideoRemoveAdPop(SZBaseActivity activity, String adUnitId, OnRewardDealListener onRewardDealListener, boolean isSetMaskerForeground) {
        super(activity, R.layout.pop_reward_video_remove_ad, true);
        this.onRewardDealListener = onRewardDealListener;
        this.activity = activity;
        this.adUnitId = adUnitId;
        setOutsideTouchable(false);
        setOnPopDismissListener(new OnPopDismissListener() {
            @Override
            public void onPopDismissListener() {
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (isSetMaskerForeground) {
                findViewById(R.id.lltBg).setForeground(activity.getResources().getDrawable(R.drawable.fg_pop_reward_video_remove_ad_night));
            }
        }
        initView();
        setViewStatus();
    }

    public RewardVideoRemoveAdPop(SZBaseActivity activity, String adUnitId, OnRewardDealListener onRewardDealListener) {
        this(activity, adUnitId, onRewardDealListener, false);
    }

    public RewardVideoRemoveAdPop(SZBaseFragment fragment, String adUnitId, OnRewardDealListener onRewardDealListener) {
        this(fragment, adUnitId, onRewardDealListener, false);
    }

    public RewardVideoRemoveAdPop(SZBaseFragment fragment, String adUnitId, OnRewardDealListener onRewardDealListener, boolean isNightMaskerMode) {
        this((SZBaseActivity) fragment.getActivity(), adUnitId, onRewardDealListener, isNightMaskerMode);
        this.fragment = fragment;
    }

    private void setViewStatus() {
        disableAllTask();
        currentTaskInfo = ADUtil.getCurrentRemoveAdRewardVideoTaskInfo();
        if (currentTaskInfo != null) {
            currentTaskInfo.logInfo();
            //超过已完成任务两小时后，未继续做任务，则任务重置
            if (ADUtil.isResetRewardTask(currentTaskInfo)) {
                ADUtil.clearCurrentRemoveAdRewardVideoTaskInfo();
                enableTask1();
                return;
            }
            int taskId = currentTaskInfo.getTaskId();
            if (taskId == 0 || (taskId != TASK_ID_1 && taskId != TASK_ID_2 && taskId != TASK_ID_3 && taskId != TASK_ID_4 && taskId != TASK_ID_5)) {
                //没有检测到任务id，则重置为第一条任务可用
                enableTask1();
            } else {
                switch (taskId) {
                    case TASK_ID_1:
                        setTask1Done();
                        viewDone2.setVisibility(View.GONE);
                        txtWatch2.setVisibility(View.VISIBLE);
                        viewCurrent2.setVisibility(View.VISIBLE);
                        txtWait2.setVisibility(View.GONE);
                        break;
                    case TASK_ID_2:
                        setTask1Done();
                        setTask2Done();
                        viewDone3.setVisibility(View.GONE);
                        txtWatch3.setVisibility(View.VISIBLE);
                        viewCurrent3.setVisibility(View.VISIBLE);
                        txtWait3.setVisibility(View.GONE);
                        break;
                    case TASK_ID_3:
                        setTask1Done();
                        setTask2Done();
                        setTask3Done();
                        viewDone4.setVisibility(View.GONE);
                        txtWatch4.setVisibility(View.VISIBLE);
                        viewCurrent4.setVisibility(View.VISIBLE);
                        txtWait4.setVisibility(View.GONE);
                        break;
                    case TASK_ID_4:
                        setTask1Done();
                        setTask2Done();
                        setTask3Done();
                        setTask4Done();
                        viewDone5.setVisibility(View.GONE);
                        txtWatch5.setVisibility(View.VISIBLE);
                        viewCurrent5.setVisibility(View.VISIBLE);
                        txtWait5.setVisibility(View.GONE);
                        break;
                    case TASK_ID_5:
                        if (onRewardDealListener != null) {
                            onRewardDealListener.onCloseRemoveAdView();
                        }
                        dismiss();
                        return;
                }
            }
        } else {
            //没有任务则第一条任务可用
            enableTask1();
        }
        setTimeShow();

    }

    private void enableTask1() {
        viewDone1.setVisibility(View.GONE);
        txtWatch1.setVisibility(View.VISIBLE);
        viewCurrent1.setVisibility(View.VISIBLE);
        txtWait1.setVisibility(View.GONE);
        lltRemoveAdTime.setVisibility(View.GONE);
    }

    private void setTask1Done() {
        txtDone1.setVisibility(View.VISIBLE);
        viewDone1.setVisibility(View.VISIBLE);
        txtWatch1.setVisibility(View.GONE);
        txtWait1.setVisibility(View.GONE);
        viewCurrent1.setVisibility(View.GONE);
    }

    private void setTask2Done() {
        txtDone2.setVisibility(View.VISIBLE);
        viewDone2.setVisibility(View.VISIBLE);
        txtWatch2.setVisibility(View.GONE);
        txtWait2.setVisibility(View.GONE);
        viewCurrent2.setVisibility(View.GONE);
    }

    private void setTask3Done() {
        txtDone3.setVisibility(View.VISIBLE);
        viewDone3.setVisibility(View.VISIBLE);
        txtWatch3.setVisibility(View.GONE);
        txtWait3.setVisibility(View.GONE);
        viewCurrent3.setVisibility(View.GONE);
    }

    private void setTask4Done() {
        txtDone4.setVisibility(View.VISIBLE);
        viewDone4.setVisibility(View.VISIBLE);
        txtWatch4.setVisibility(View.GONE);
        txtWait4.setVisibility(View.GONE);
        viewCurrent4.setVisibility(View.GONE);
    }

    private void setTask5Done() {
        txtDone5.setVisibility(View.VISIBLE);
        viewDone5.setVisibility(View.VISIBLE);
        txtWatch5.setVisibility(View.GONE);
        txtWait5.setVisibility(View.GONE);
        viewCurrent5.setVisibility(View.GONE);
    }

    //将所有任务置为不可用，等待执行状态
    private void disableAllTask() {
        viewDone1.setVisibility(View.VISIBLE);
        viewDone2.setVisibility(View.VISIBLE);
        viewDone3.setVisibility(View.VISIBLE);
        viewDone4.setVisibility(View.VISIBLE);
        viewDone5.setVisibility(View.VISIBLE);

        txtWatch1.setVisibility(View.GONE);
        txtWatch2.setVisibility(View.GONE);
        txtWatch3.setVisibility(View.GONE);
        txtWatch4.setVisibility(View.GONE);
        txtWatch5.setVisibility(View.GONE);

        txtDone1.setVisibility(View.GONE);
        txtDone2.setVisibility(View.GONE);
        txtDone3.setVisibility(View.GONE);
        txtDone4.setVisibility(View.GONE);
        txtDone5.setVisibility(View.GONE);

        viewCurrent1.setVisibility(View.GONE);
        viewCurrent2.setVisibility(View.GONE);
        viewCurrent3.setVisibility(View.GONE);
        viewCurrent4.setVisibility(View.GONE);
        viewCurrent5.setVisibility(View.GONE);

        txtWait1.setVisibility(View.VISIBLE);
        txtWait2.setVisibility(View.VISIBLE);
        txtWait3.setVisibility(View.VISIBLE);
        txtWait4.setVisibility(View.VISIBLE);
        txtWait5.setVisibility(View.VISIBLE);

    }

    private void setTimeShow() {
        if (txtTime == null) {
            return;
        }
        if (currentTaskInfo != null) {
            if (lltRemoveAdTime.getVisibility() == View.GONE) {
                getContentView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (lltRemoveAdTime.getHeight() > 0) {
                            getContentView().getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            int heightOld = getContentView().getHeight();
                            int heightNew = heightOld + lltRemoveAdTime.getHeight() + SZUtil.dip2px(20);
                            int y = SZUtil.getScreenHeight(baseActivity) - heightNew + ((SZBaseActivity) baseActivity).getStatusBarHeight();
                            update(0, y, SZUtil.getScreenWidth(baseActivity), heightNew);
                        }
                    }
                });
            }
            lltRemoveAdTime.setVisibility(View.VISIBLE);
            txtTime.setText(SZDateUtil.getNearByTimeShow(currentTaskInfo.getEndTime(), false));
        } else {
            if (lltRemoveAdTime.getVisibility() == View.VISIBLE) {
                getContentView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (lltRemoveAdTime.getHeight() > 0) {
                            getContentView().getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            int heightOld = getContentView().getHeight();
                            int heightNew = heightOld - lltRemoveAdTime.getHeight() - SZUtil.dip2px(20);
                            int y = SZUtil.getScreenHeight(baseActivity) - heightNew + activity.getStatusBarHeight();
                            update(0, y, SZUtil.getScreenWidth(baseActivity), heightNew);
                        }
                    }
                });
            }
            lltRemoveAdTime.setVisibility(View.GONE);
        }
    }


    private void loadReward(final int taskId) {
//        if(currentTaskInfo!=null){
//            if(System.currentTimeMillis()-currentTaskInfo.getDoneTime()<SZDateUtil.ONE_MINUTE){
//                SZToast.warningLong("请间隔一分钟后再看！");
//                return;
//            }
//        }
        showBar();
        new AdRewardManager(activity, new AdRewardManager.OnRewardLoadListener() {

            @Override
            public void onRewardArrived(boolean isRewardValid, int rewardType, Bundle extraInfo) {
                SZUtil.logError("激励视频，成功了：" + isRewardValid);
                ADUtil.setCurrentRemoveAdRewardVideoTaskInfo(taskId);
                setViewStatus();
            }

            @Override
            public void onError() {
                closeBar();
                SZUtil.logError("激励视频，出错了！");
                SZToast.errorLong("视频观看出错，请稍后再试！");
            }

            @Override
            public void onShow() {
                closeBar();
            }

            @Override
            public void onClose(boolean isRewardValid) {
                if (isRewardValid) {
                    if (TASK_ID_5 == taskId) {
                        showRewardRemoveAdAllDonePop();
                    } else {
                        if (Looper.getMainLooper() == Looper.myLooper()) {
                            SZUtil.logError("主线程：" + "恭喜获得" + taskId + "小时免广告特权！");
                            SZToast.successLong("恭喜获得" + taskId + "小时免广告特权！");
                        } else {
                            SZUtil.logError("子线程：" + "恭喜获得" + taskId + "小时免广告特权！");
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    SZToast.successLong("恭喜获得" + taskId + "小时免广告特权！");
                                }
                            });
                        }
                    }
                } else {
                    try {
                        if (fragment != null) {
                            fragment.showErrorAlert("任务失败", "按要求完整观看视频或浏览页面，才能获得特权哦~", "确定");
                        } else if (activity != null) {
                            activity.showErrorAlert("任务失败", "按要求完整观看视频或浏览页面，才能获得特权哦~", "确定");
                        }
                        return;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (Looper.getMainLooper() == Looper.myLooper()) {
                        SZUtil.logError("主线程：完整观看视频后才能获得特权哦~");
                        SZToast.infoLong("完整观看或浏览后才能获得特权哦~");
                    } else {
                        SZUtil.logError("子线程：完整观看视频后才能获得特权哦~");
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                SZToast.infoLong("完整观看或浏览后才能获得特权哦~");
                            }
                        });
                    }
                }
                SZUtil.logError("激励视频，关闭了！");
            }

        }).loadAd(adUnitId);
    }

    private RewardVideoRemoveAdAllDonePop showRewardRemoveAdAllDonePop() {
        RewardVideoRemoveAdAllDonePop rewardVideoRemoveAdPop = new RewardVideoRemoveAdAllDonePop(activity, false);
        rewardVideoRemoveAdPop.setAnimationStyle(0);
        rewardVideoRemoveAdPop.showOnAnchorFromBottom(activity.getBaseView());
        return rewardVideoRemoveAdPop;
    }

    private void showBar() {
        if (fragment != null) {
            fragment.showBar(false, false);
        } else if (activity != null) {
            activity.showBar(false, false);
        }
    }

    private void closeBar() {
        if (fragment != null) {
            fragment.closeBar();
        } else if (activity != null) {
            activity.closeBar();
        }
    }

    private void initView() {
        lltRemoveAdTime = findViewById(R.id.lltRemoveAdTime);
        txtTime = findViewById(R.id.txtTime);
        txtWait1 = findViewById(R.id.txtWait1);
        txtDone1 = findViewById(R.id.txtDone1);
        txtWatch1 = findViewById(R.id.txtWatch1);
        viewDone1 = findViewById(R.id.viewDone1);
        viewCurrent1 = findViewById(R.id.viewCurrent1);
        txtWait2 = findViewById(R.id.txtWait2);
        txtDone2 = findViewById(R.id.txtDone2);
        txtWatch2 = findViewById(R.id.txtWatch2);
        viewDone2 = findViewById(R.id.viewDone2);
        viewCurrent2 = findViewById(R.id.viewCurrent2);
        txtWait3 = findViewById(R.id.txtWait3);
        txtDone3 = findViewById(R.id.txtDone3);
        txtWatch3 = findViewById(R.id.txtWatch3);
        viewDone3 = findViewById(R.id.viewDone3);
        viewCurrent3 = findViewById(R.id.viewCurrent3);
        txtWait4 = findViewById(R.id.txtWait4);
        txtDone4 = findViewById(R.id.txtDone4);
        txtWatch4 = findViewById(R.id.txtWatch4);
        viewDone4 = findViewById(R.id.viewDone4);
        viewCurrent4 = findViewById(R.id.viewCurrent4);
        txtWait5 = findViewById(R.id.txtWait5);
        txtDone5 = findViewById(R.id.txtDone5);
        txtWatch5 = findViewById(R.id.txtWatch5);
        viewDone5 = findViewById(R.id.viewDone5);
        viewCurrent5 = findViewById(R.id.viewCurrent5);
        getContentView().findViewById(R.id.imgClose).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismissPop();
            }
        });
        txtWatch1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadReward(TASK_ID_1);
            }
        });
        txtWatch2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadReward(TASK_ID_2);
            }
        });
        txtWatch3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadReward(TASK_ID_3);
            }
        });
        txtWatch4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadReward(TASK_ID_4);
            }
        });
        txtWatch5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadReward(TASK_ID_5);
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
        }
    };
}
